package com.zshan.clinic.web.config;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Configuration
public class JacksonConfig {

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer customDateDeserializer() {
        return builder -> {
            // 支持 java.util.Date 多格式
            builder.deserializerByType(Date.class, new CustomDateDeserializer());
            // 支持 LocalTime 格式，如 "08:30"
            DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm");
            builder.deserializerByType(LocalTime.class, new LocalTimeDeserializer(timeFormatter));
            builder.serializerByType(LocalTime.class, new LocalTimeSerializer(timeFormatter));
        };
    }

    public static class CustomDateDeserializer extends JsonDeserializer<Date> {

        private final List<SimpleDateFormat> formats = Arrays.asList(
                new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"),
                new SimpleDateFormat("yyyy-MM-dd"),
                new SimpleDateFormat("yyyy/MM/dd")
        );

        @Override
        public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
            String value = p.getText().trim();
            for (SimpleDateFormat format : formats) {
                try {
                    return format.parse(value);
                } catch (ParseException ignored) {
                }
            }
            throw new RuntimeException("Unparseable date: " + value);
        }
    }
}


